import * as path from 'path';
import * as cp from 'child_process';
import { logInfo, logError } from './helper/utils';

interface IMessage {
  message: any;
  type: boolean;
  repoName: string;
  tag: string;
}

export default (): cp.ChildProcess => {
  let WORKER: cp.ChildProcess;

  if (process.env.NODE_ENV === 'development') {
    WORKER = cp.fork(path.join(__dirname, './workflow/index.ts'), [], { execArgv: ["-r", "ts-node/register"] });
  } else {
    WORKER = cp.fork(path.join(__dirname, './workflow/index.js'));
  }

  WORKER.on('error', async (err) => await logError('fork', 'error', err));

  WORKER.on('message', async ({ message, type, repoName, tag }: IMessage) => {
    if (process.env.NODE_ENV === 'test') {
      !type && await logError(repoName, tag, message);
    } else {
      await (type ? logInfo : logError)(repoName, tag, message);
    }
  });

  WORKER.on('disconnect', console.error);
  return WORKER;
}
